package lumis.service.group;

import org.w3c.dom.Node;

import lumis.doui.source.ISourceData;
import lumis.doui.source.Source;
import lumis.doui.source.TabularData;
import lumis.doui.source.postloadprocessor.IPostLoadProcessor;
import lumis.portal.PortalException;
import lumis.portal.authentication.SessionConfig;
import lumis.portal.channel.ChannelConfig;
import lumis.portal.manager.ManagerFactory;
import lumis.util.ITransaction;
import lumis.util.XmlUtil;

/**
 * Post load processor that removes the prefix from a principal shortId.
 * In the source there must be a field <code>channelId</code> that
 * references the channel whose prefix is to be removed. 
 * The parameter <code>nameFieldId</code> specifies the field that will be processed, 
 * removing the channel prefix from it. 
 * 
 * <p>
 * Example usage:
 * <xmp>
 *<postLoadProcessor className="lumis.service.group.PrefixRemovalPostLoadProcessor">
 *	<parameters>
 *		<parameter name="nameFieldId">alias</parameter>
 *	</parameters>
 *</postLoadProcessor>
 * </xmp>
 * 
 * @version $Revision: 10825 $ $Date: 2009-08-04 12:36:40 -0300 (Tue, 04 Aug 2009) $
 * @since 5.0.0
 */
public class PrefixRemovalPostLoadProcessor implements IPostLoadProcessor
{
	public void processSource(SessionConfig sessionConfig, Source source, Node parametersNode, ITransaction transaction) throws PortalException
	{
		String nameFieldId = XmlUtil.readNodeString("parameter[@name='nameFieldId']", parametersNode);
		
		TabularData tabularData = (TabularData)source.getData();
		for(ISourceData row : tabularData.getRows())
		{
			String channelId = row.get("channelId", String.class);
			if(channelId != null)
			{
				ChannelConfig channelConfig = ManagerFactory.getChannelManager().get(sessionConfig, channelId, transaction);
				String localGroupPrefix = channelConfig.getLocalGroupPrefix();
				String fullNameField = row.get(nameFieldId, String.class);
				String nameField = fullNameField.substring(localGroupPrefix.length()+1);
				row.put(nameFieldId, nameField);
			}
		}
	}
}